import { h } from "koishi"

export const name = "-lnnbot-defs-register"

export function apply(ctx) {
  ctx.component("i18n:object", async (attrs, children, session) => {
    return session.i18n(attrs.path, attrs.data)
  }, { session: true })

  ctx.component("i18n:langname", async (attrs, _, session) => {
    if (attrs.path) {
      const paths = (Array.isArray(attrs.path) ? attrs.path : [attrs.path]).map(p => `${p}.${attrs.code}`)
      const e = session.i18n([...paths, ""])
      if (e.length) return e
    }

    let locales = [
      ...session.channel?.locales || [],
      ...session.guild?.locales || [],
    ]
    if (ctx.root.config.i18n.output === "prefer-user") {
      locales.unshift(...session.user?.locales || [])
    } else {
      locales.push(...session.user?.locales || [])
    }
    locales.unshift(...session.locales || [])
    locales.push(ctx.root.config.i18n.locales[0])
    locales = locales.filter(l => l.match(/^[a-z]{2}(-|$)|^[a-pr-z][a-z]{2}(-|$)/))
    ctx.logger.debug(locales)

    //for (const i of locales)
    //  try {
    //    return new Intl.DisplayNames([i], { type: "language" }).of(attrs.code)
    //  } catch {}
    //return String(attrs.code)
    return new Intl.DisplayNames(locales, { type: "language" }).of(attrs.code)
  }, { session: true })

  ctx.component("panguspace", async (attrs, children, session) => {
    children = await session.transform(children)
    if (
      !attrs.after &&
      children[0]?.type === "text" &&
      !children[0].attrs.content.match(/^\p{Script_Extensions=Han}/u)
    ) children[0].attrs.content = " " + children[0].attrs.content
    if (
      !attrs.before &&
      children.at(-1)?.type === "text" &&
      !children.at(-1).attrs.content.match(/\p{Script_Extensions=Han}$/u)
    ) children.at(-1).attrs.content += " "
    return children
  })

  ctx.$commander.domain("fragment", source => h.parse(source))
}
